package cn.wellwan.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.config.ConnectionConfig;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidParameterSpecException;
import java.util.Arrays;
import java.util.Map;


public class HttpClient {

    private ConnectionConfig connectionConfig = ConnectionConfig.custom().setBufferSize(4128).build();
    private CloseableHttpClient httpClient = HttpClients.custom().setDefaultConnectionConfig(connectionConfig).build();
    private final RestTemplate rest = new RestTemplate();
    /**
     * get请求-返回JSONObject
     */
    public JSONObject getJSON(String url) {
        try {
            RequestBuilder builder = RequestBuilder.get(url);
            HttpUriRequest request = builder.build();

            return httpClient.execute(request,getResponseHandler());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * post请求-返回JSONObject
     */
    public JSONObject postJSON(String url, Map<String, Object> params) {
        String json=null;
        if(params!=null && params.size() > 0) json= JSON.toJSONString(params);
        return postJSON(url, json);
    }

    /**
     * post请求-返回JSONObject
     */
    public JSONObject postJSON(String url, String json) {
        try {
            HttpPost httpPost = new HttpPost(url);
            if(StringUtils.isNotBlank(json)){
                StringEntity entity = new StringEntity(json,"utf-8");//解决中文乱码问题
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                httpPost.setEntity(entity);
            }
            return httpClient.execute(httpPost,getResponseHandler());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /*
     * 指定响应返回类型=JSONObject
     */
    private ResponseHandler<JSONObject> getResponseHandler() {
        ResponseHandler<JSONObject> handler = new ResponseHandler<JSONObject>() {
            public JSONObject handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String json = EntityUtils.toString(entity,"UTF-8");
                    return JSON.parseObject(json);
                }
                return null;
            }
        };
        return handler;
    }


    public static void main(String[] args) {


        HttpClient httpClient = new HttpClient();
//        JSONObject json = httpClient.getJSON("https://music.163.com/#/artist?id=12146142");

        String httpclient = httpClient.httpclient(null, "https://music.163.com/#/artist?id=12146142", HttpMethod.GET, String.class);
        System.out.println(httpclient);
    }
    public JSONObject getUserInfo(String encryptedData,String sessionkey,String iv){
        // 被加密的数据
        byte[] dataByte = Base64.decode(encryptedData);
        // 加密秘钥
        byte[] keyByte = Base64.decode(sessionkey);
        // 偏移量
        byte[] ivByte = Base64.decode(iv);
        try {
            // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
            int base = 16;
            if (keyByte.length % base != 0) {
                int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
                byte[] temp = new byte[groups * base];
                Arrays.fill(temp, (byte) 0);
                System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
                keyByte = temp;
            }
            // 初始化
            Security.addProvider(new BouncyCastleProvider());
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding","BC");
            SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
            AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
            parameters.init(new IvParameterSpec(ivByte));
            cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
            byte[] resultByte = cipher.doFinal(dataByte);
            if (null != resultByte && resultByte.length > 0) {
                String result = new String(resultByte, "UTF-8");
                return JSONObject.parseObject(result);
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidParameterSpecException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            e.printStackTrace();
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        }
        return null;
    }

    <T> T httpclient(Map<String,Object> params, String url, HttpMethod httpMethod, Class<T> var4) {
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            org.springframework.http.HttpEntity requestEntity = new org.springframework.http.HttpEntity(params, headers);

            ResponseEntity<T> entity = rest.exchange(url, httpMethod, requestEntity, var4, new Object[0]);
            T result = entity.getBody();
            HttpHeaders headers1 = entity.getHeaders();
            MediaType contentType = headers1.getContentType();
            String subtype = contentType.getSubtype();
//        if ("json".equals(subtype)) {
//            try {
//                return null;
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }
//        }
        return result;
    }
}
